package com.xxxx.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminVo;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Workflow;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.IWorkflowService;
import com.xxxx.server.utils.AdminUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhao
 * @since 2022-03-24
 */
@RestController
@RequestMapping("/workflow")
public class WorkflowController {

    @Autowired
    private IWorkflowService workflowService;

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "根据账号id获取申请列表")
    @GetMapping("/list")
    public List<Workflow> getAllWorkflows(){
        Integer adminId = (AdminUtils.getCurrentAdmin().getId()); //账号id
        String adminIdString = adminId.toString();
        QueryWrapper<Workflow> workflowQueryWrapper = new QueryWrapper<>();
        workflowQueryWrapper.eq("status",0); //申请中的
        workflowQueryWrapper.orderByDesc("createtime");
        List<Workflow> list = workflowService.list(workflowQueryWrapper); //数据库中所有审核中的数据
        List<Workflow> finalList = new ArrayList<>(); //对应账号的数据
        if(list.size() > 0){
            for (Workflow workflow : list) {
                String roleflow = workflow.getRoleflow();
                if(StringUtils.isNotBlank(roleflow)) { //审批人不为空
                    List<String> roleflowList = Arrays.asList(roleflow.split(",")); // 审批人字符串list
                    String accountflow = workflow.getAccountflow();
                    if (StringUtils.isNotBlank(accountflow)) { //已同意的审批人不为空
                        List<String> accountflowStrings = Arrays.asList(accountflow.split(","));  // 已同意的审批人字符串list
                        if(roleflowList.get(accountflowStrings.size()).equals(adminIdString)){
                            //获取审批人的名称
                            workflow.setAllowName(getAdminNames(workflow.getRoleflow()));
                            //获取已同意审批人的名称
                            workflow.setAllowedName(getAdminNames(workflow.getAccountflow()));
                            //获取申请人名称
                            workflow.setAccountName(getAdminNames(workflow.getAccount_id().toString()));
                            finalList.add(workflow);

                        }
                    } else {                               //已同意的审批人为空 取第一个审批人
                        if(adminIdString.equals(roleflowList.get(0))){
                            //获取审批人
                            workflow.setAllowName(getAdminNames(workflow.getRoleflow()));
                            //获取申请人名称
                            workflow.setAccountName(getAdminNames(workflow.getAccount_id().toString()));
                            finalList.add(workflow);
                        }
                    }
                }

            }
        }
        return finalList;
    }

    @ApiOperation(value = "新增流程")
    @PostMapping("/addWorkflows")
    public RespBean addWorkflows(@RequestBody Workflow workflow){
        Integer adminId = (AdminUtils.getCurrentAdmin().getId()); //账号id
        workflow.setAccount_id(adminId);
        workflow.setCreatetime(LocalDateTime.now());
        if(workflowService.save(workflow)){
            return RespBean.success("新增成功!");
        }
        return RespBean.success("新增失败!");
    }

    @ApiOperation(value = "申请列表")
    @GetMapping("/myList")
    public List<Workflow> myWorkflowsList(Workflow workflow){
        Integer adminId = (AdminUtils.getCurrentAdmin().getId()); //账号id
        QueryWrapper<Workflow> workflowQueryWrapper = new QueryWrapper<>();
        workflowQueryWrapper.eq("account_id",adminId);
        if(workflow.getStatus() != null){
            workflowQueryWrapper.eq("status",workflow.getStatus());
        }
        LinkedList<Workflow> WorkflowList = new LinkedList<>();
        //数据处理
        for (Workflow workflow1 : workflowService.list(workflowQueryWrapper)) {
            //获取审批人的名称
            workflow1.setAllowName(getAdminNames(workflow1.getRoleflow()));
            //获取已同意审批人的名称
            workflow1.setAllowedName(getAdminNames(workflow1.getAccountflow()));
            //状态翻译
            if(workflow1.getStatus() == 0){
                workflow1.setStatusString("申请中");
            }
            if(workflow1.getStatus() == 1){
                workflow1.setStatusString("已拒绝");
            }
            if(workflow1.getStatus() == 2){
                workflow1.setStatusString("已完成");
            }
            WorkflowList.add(workflow1);
        }
        return WorkflowList;
    }

    @ApiOperation(value = "审批流程")
    @PostMapping("/updateWorkflows")
    public RespBean updateWorkflows(@RequestBody Workflow workflow){
        Integer adminId = (AdminUtils.getCurrentAdmin().getId()); //账号id
        Workflow byId = workflowService.getById(workflow.getId());
        if (byId != null) {
            if (workflow.getAllow() == 0) { //允许
                if (StringUtils.isNotBlank(byId.getAccountflow())) {  //已同意审批人添加操作
                    String accountflow = byId.getAccountflow();
                    List<String> accountflowList = Arrays.asList(accountflow.split(","));
                    List arrList = new ArrayList(accountflowList);
                    arrList.add(adminId.toString());
                    String join = StringUtils.join(arrList, ",");
                    byId.setAccountflow(join);

                    //对比流程 看是否走完
                    String roleflow = byId.getRoleflow();
                    List<String> roleflowList = Arrays.asList(roleflow.split(","));
                    if (roleflowList.size() == arrList.size()) {
                        byId.setStatus(2);
                    }
                } else {
                    byId.setAccountflow(adminId.toString());
                }
            } else {  //拒绝
                byId.setStatus(1);
            }
        }else {
            return RespBean.error("审批失败!");
        }
        if(workflowService.updateById(byId)){
            return RespBean.success("审批成功!");
        }
        return RespBean.error("审批失败!");
    }

    /**
     * 获取操作员名称
     * @return
     */
    private String getAdminNames(String adminids){
        if(StringUtils.isNotBlank(adminids)) {
            List<String> roleflowList = Arrays.asList(adminids.split(","));
            ArrayList arrayList = new ArrayList();
            for (String adminid : roleflowList) {
                Admin byId = adminService.getById(adminid);  //牺牲数据库性能 , 可以在redis做缓存减轻数据库压力
                if(byId != null) {
                    arrayList.add(byId.getName());
                }else {
                    arrayList.add("*不存在的审批人");
                }
            }
            return StringUtils.join(arrayList,"->");
        }
        return null;
    }

    @ApiOperation(value = "获取所有操作员名称和id")
    @GetMapping("/getAllName")
    public List<AdminVo> getAllName(){
        Integer adminId = (AdminUtils.getCurrentAdmin().getId()); //账号id
        LinkedList<AdminVo> AdminList = new LinkedList<>();
        List<Admin> enabled = adminService.list(new QueryWrapper<Admin>().eq("enabled", 1).ne("id",adminId));
        for (Admin admin : enabled) {   //将其他信息置空
            AdminVo admin1 = new AdminVo();
            admin1.setName(admin.getName());
            admin1.setId(admin.getId());
            AdminList.add(admin1);
        }
        return AdminList;
    }
}
